import React, { PureComponent } from 'react'
import { Button, Form, Input, InputNumber, Select, Icon, Alert, notification } from 'antd'
import Modal from 'kenote-react-admin-modal'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { adminsGroupActions } from 'reduxs'
import _ from 'lodash'
import 'styles/modal.scss'

const FormItem = Form.Item
const Option = Select.Option
const TextArea = Input.TextArea

@connect(
  state => ({
    createPending   : state.AdminsGroup.createPending,
    createError     : state.AdminsGroup.createError,
    createMessage   : state.AdminsGroup.createMessage,
    listData        : state.AdminsGroup.listData,
    auth            : state.Passport.auth,
    teams           : state.Passport.teams
  }),
  dispatch => ({
    actions: bindActionCreators({...adminsGroupActions}, dispatch)
  })
)
@Form.create()
export default class AddAdminsGroupModal extends PureComponent {

  state = {
    disabled: true,
    alert: null
  }

  constructor (props) {
    super(props)
    this._Modal = null
    this._Form = null
  }
  
  componentWillReceiveProps (nextProps) {
    const { createError, createMessage } = nextProps
    if (createError > 0 && createMessage !== this.props.createMessage) {
      this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px' }}
          message={createMessage}
          type="error"
          showIcon
          key="aaa"
        />
      )})
    }
    if (createError === 0 && createMessage !== this.props.createMessage) {
      this._Modal.handleOnCancel()
      notification.info({
        message: `系统提示`,
        description: `用户组创建成功！`,
        duration: 8,
        placement: 'bottomRight'
      })
    }
  }
  
  render () {
    const { visible, onCancel, form, createPending, auth, teams } = this.props
    const { getFieldDecorator } = form
    const { group } = auth
    let minLevel = 1001
    let maxLevel = group.level - 1
    const options = {
      ref: view => this._Modal = view,
      visible: visible,
      onCancel: onCancel,
      title: '创建用户组',
      footer: [
        <Button
          onClick={() => this._Modal.handleOnCancel()}
          >
          取消
        </Button>,
        <Button
          type="primary"
          loading={createPending}
          onClick={this.handleSubmit}
          >
          确定
        </Button>
      ],
      width: 600,
      maskClosable: false
    }
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }
    return (
      <Modal {...options}>
        <br />
        <Form 
          ref={ view => this._Form = view }
          layout="horizontal" 
          onSubmit={this.handleSubmit}
          >
          {createPending ? null : (
            <QueueAnim component="div" type={['bottom', 'top']} leaveReverse>
              {this.state.alert ? this.state.alert : null}
            </QueueAnim>
          )}
          <FormItem 
            {...formItemLayout} 
            label="用户组名称" 
            >
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '用户组名称不能为空!' }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="隶属团队" 
            >
            {getFieldDecorator('team', {
              rules: [{ required: true, message: '至少要选择一个团队!' }],
            })(
              <Select
                placeholder="请选择相应团队..." 
                size="Small"
                mode="multiple"
                >
                {teams && _.keys(teams).map((item, i) => {
                  return (
                    <Option key={i} value={item}>{teams[item]}</Option>
                  )
                })}
              </Select>
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="用户组权级" 
            >
            {getFieldDecorator('level', {
              initialValue: minLevel
            })(
              <InputNumber min={minLevel} max={maxLevel} />
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="用户组描述" 
            >
            {getFieldDecorator('desc', {})(
              <TextArea rows={4} autosize={{ minRows: 4, maxRows: 4 }} />
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
  
  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (values.level === 9999) {
          _.unset(values, 'level')
        }
        this.props.actions.create(values)
      }
    })
  }
}